package com.example.web.controller;

import com.example.web.annotation.RequiresPermission;
import com.example.web.entity.Role;
import com.example.web.entity.Result;
import com.example.web.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色控制器
 */
@RestController
@RequestMapping("/api/system/role")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 获取角色列表
     */
    @GetMapping("/list")
    @RequiresPermission("system:role:list")
    public Result<List<Role>> list() {
        List<Role> roles = roleService.getAllRoles();
        return Result.success(roles);
    }

    /**
     * 获取角色详情
     */
    @GetMapping("/{id}")
    @RequiresPermission("system:role:query")
    public Result<Role> getInfo(@PathVariable Long id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    /**
     * 新增角色
     */
    @PostMapping
    @RequiresPermission("system:role:add")
    public Result<Void> add(@RequestBody Role role) {
        int rows = roleService.addRole(role);
        return rows > 0 ? Result.success() : Result.error("新增角色失败");
    }

    /**
     * 修改角色
     */
    @PutMapping
    @RequiresPermission("system:role:edit")
    public Result<Void> update(@RequestBody Role role) {
        int rows = roleService.updateRole(role);
        return rows > 0 ? Result.success() : Result.error("修改角色失败");
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @RequiresPermission("system:role:remove")
    public Result<Void> remove(@PathVariable Long id) {
        int rows = roleService.deleteRoleById(id);
        return rows > 0 ? Result.success() : Result.error("删除角色失败");
    }

    /**
     * 批量删除角色
     */
    @DeleteMapping("/batch/{ids}")
    @RequiresPermission("system:role:batchRemove")
    public Result<Void> batchRemove(@PathVariable Long[] ids) {
        int rows = roleService.deleteRoleByIds(ids);
        return rows > 0 ? Result.success() : Result.error("批量删除角色失败");
    }

    /**
     * 分配菜单权限
     */
    @PostMapping("/{roleId}/menus")
    @RequiresPermission("system:role:assignMenus")
    public Result<Void> assignMenus(@PathVariable Long roleId, @RequestBody Long[] menuIds) {
        int rows = roleService.assignMenus(roleId, menuIds);
        return rows > 0 ? Result.success() : Result.error("分配菜单权限失败");
    }
}